//
//  SearchResultVC.swift
//  LeTu
//
//  Created by g1 on 2024/1/14.
//

import UIKit

class SearchResultVC: BaseViewController {

    private var viewModel: SearchResultVM
    private let flowlayout = WaterfallMutiSectionFlowLayout()
    
    init(keyword: String) {
        self.viewModel = SearchResultVM(keyword: keyword)
        super.init()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        configUI()
        
        guard viewModel.keyword.count > 0 else { return }
        collectCollectionView.headerBeginRefreshing()
    }
    
    // MARK: - getData
    func getData(isLoad: Bool) {
        
        if isLoad == false {
            collectCollectionView.footerResetNoMoreData()
        }
        
        viewModel.getCitys(isLoad: isLoad) { [weak self] dialog in
            
            guard let strongSelf = self else { return }
            
            DispatchQueue.main.async {
                
                if isLoad {
                    strongSelf.collectCollectionView.footerEndRefreshing()
                } else {
                    strongSelf.collectCollectionView.headerEndRefreshing()
                }
                
                if dialog.code != 200 {
                    strongSelf.showMessage(message: dialog.message)
                }
                
                strongSelf.collectCollectionView.footerEndRefreshingWithNoMoreData()
                strongSelf.collectCollectionView.reloadData()
                
            }
            
        }
        
    }
    
    // MARK: - configUI
    func configUI() {
                
        view.addSubview(searchBar)
        view.addSubview(collectCollectionView)
        
        searchBar.snp.makeConstraints { make in
            make.left.top.right.equalToSuperview()
            make.height.equalTo(Size.navigationBarHeight)
        }
        collectCollectionView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(searchBar.snp.bottom)
        }
        
        flowlayout.delegate = self
        collectCollectionView.delegate = self
        collectCollectionView.dataSource = self
        collectCollectionView.register(cellClass: CollectItemCollectionViewCell.self)
        collectCollectionView.register(cellClass: BaseEmptyCollectionViewCell.self)
        collectCollectionView.register(headerClass: BaseEmptyHeaderCollectionReusableView.self)
        collectCollectionView.register(footerClass: BaseEmptyFooterCollectionReusableView.self)
        collectCollectionView.addRefreshHeaderCallback { [weak self] in
            guard let strongSelf = self else { return }
            strongSelf.getData(isLoad: false)
        }
        collectCollectionView.addRefreshFooterCallback { [weak self] in
            guard let strongSelf = self else { return }
            strongSelf.getData(isLoad: true)
        }
        
        searchBar.setKeyword(viewModel.keyword)
        
        searchBar.searchHolder = { [weak self] keyword in
            guard let strongSelf = self else { return }
            strongSelf.viewModel.keyword = keyword
            strongSelf.getData(isLoad: false)
        }
        searchBar.rightItemHolder = { [weak self] in
            guard let strongSelf = self else { return }
            strongSelf.backAction()
        }
    }
    private lazy var searchBar = SearchScenicNavBar(placeholder: "搜索景点/目的地".localized, isClearContent: false)
    private lazy var collectCollectionView : UICollectionView = {
        let collectCollectionView = UICollectionView(frame: .zero, collectionViewLayout: flowlayout)
        collectCollectionView.backgroundColor = .app_white
        return collectCollectionView
    }()
    
    required public init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

extension SearchResultVC: WaterfallMutiSectionDelegate, UICollectionViewDelegate, UICollectionViewDataSource {

    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        if kind == UICollectionView.elementKindSectionHeader {
            let header = collectionView.dequeueReusableViewHeader(BaseEmptyHeaderCollectionReusableView.self, indexPath: indexPath)
            header.backgroundColor = .app_viewBackgroundColor
            return header
        } else {
            let footer = collectionView.dequeueReusableViewFooter(BaseEmptyFooterCollectionReusableView.self, indexPath: indexPath)
            return footer
        }
    }
    func insetForSection(collectionView collection: UICollectionView, layout: WaterfallMutiSectionFlowLayout, section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 16, left: 10, bottom: 0, right: 10)
    }
    func referenceSizeForHeader(collectionView collection: UICollectionView, layout: WaterfallMutiSectionFlowLayout, section: Int) -> CGSize {
        return CGSize(width: screenWidth, height: 0.01)
    }
    func referenceSizeForFooter(collectionView collection: UICollectionView, layout: WaterfallMutiSectionFlowLayout, section: Int) -> CGSize {
        return CGSize(width: screenWidth, height: 0.01)
    }
    func lineSpacing(collectionView collection: UICollectionView, layout: WaterfallMutiSectionFlowLayout, section: Int) -> CGFloat {
        return 10
    }
    func interitemSpacing(collectionView collection: UICollectionView, layout: WaterfallMutiSectionFlowLayout, section: Int) -> CGFloat {
        return 10
    }
    func columnNumber(collectionView collection: UICollectionView, layout: WaterfallMutiSectionFlowLayout, section: Int) -> Int {
        return viewModel.sourceArr.count == 0 ? 1:2
    }
    func heightForRowAtIndexPath(collectionView collection: UICollectionView, layout: WaterfallMutiSectionFlowLayout, indexPath: IndexPath, itemWidth: CGFloat) -> CGFloat {
        guard viewModel.sourceArr.count > 0 else {
            return collectCollectionView.height
        }
        let collectModel = viewModel.sourceArr[indexPath.row]
        var cellHeight = CollectItemCollectionViewCell.getFixCellHeight()
        let itemW = (screenWidth-20-10)/2
        if let url = URL(string: collectModel.picUrl) {
            cellHeight += XHWebImageAutoSize.imageHeight(for: url, layoutWidth: itemW, estimateHeight: itemW)
        }
        return cellHeight
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return viewModel.sourceArr.count == 0 ? 1:viewModel.sourceArr.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if viewModel.sourceArr.count == 0 {
            let cell = collectionView.dequeueReusableCell(BaseEmptyCollectionViewCell.self, indexPath: indexPath)
            cell.setInfo(iconName: "nodata", title: "暂无数据".localized)
            return cell
        }
        let cell = collectionView.dequeueReusableCell(CollectItemCollectionViewCell.self, indexPath: indexPath)
        let scenicModel = viewModel.sourceArr[indexPath.row]
        cell.setScenicModel(scenicModel)
        cell.imgView.sd_setImage(with: URL.encodedURL(string: scenicModel.picUrl)) { img, error, type, url in
            
            if let image = img, let url = url {
                
                XHWebImageAutoSize.storeImageSize(image, for: url) { [weak self] (result) in
                    
                    guard let strongSelf = self else { return }
                    XHWebImageAutoSize.reloadStateFromCache(for: url)
                    strongSelf.collectCollectionView.xh_reloadData(for: url)
                    
                }
                
            }
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        guard viewModel.sourceArr.count > 0 else { return }
        let scenicModel = viewModel.sourceArr[indexPath.row]
        show(ScenicDetailVC(scenicModel: scenicModel), sender: nil)
    }

}

